<template>
  <div ref="warpper">
    <slot />
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import BScroll from 'better-scroll'
@Component({})
export default class extends Vue {
  @Prop({ default: 1 }) probeType!: number
  @Prop({ default: false }) scrollx!: boolean
  @Prop({ default: true }) click!: boolean
  @Prop({ default: false }) listenScroll!: boolean
  @Prop({ default: 0 }) data!: number
  @Prop({ default: false }) pullup!: boolean
  @Prop({ default: false }) beforeScroll!: boolean
  @Prop({ default: 20 }) refreshDelay!: number
  @Prop({ default: 0 }) scrollValue!: number

  private scroll: any // eslint-disable-line
  mounted() {
    setTimeout(() => {
      this._initScroll()
    }, 20)
  }

  @Watch('data')
  onChangeValue() {
    setTimeout(() => {
      this.refresh(this.scrollValue)
    }, this.refreshDelay)
  }
  _initScroll() {
    if (!this.$refs.warpper) {
      return
    }
    this.scroll = new BScroll(this.$refs.warpper as HTMLElement, {
      probeType: this.probeType,
      scrollX: this.scrollx,
      click: this.click
    })
    if (this.listenScroll) {
      this.scroll.on('scroll', (pos: object) => {
        this.$emit('scroll', pos)
      })
    }

    if (this.pullup) {
      this.scroll.on('scrollEnd', () => {
        if (this.scroll.y <= this.scroll.maxScrollY + 50) {
          this.$emit('scrollToEnd')
        }
      })
    }

    if (this.beforeScroll) {
      this.scroll.on('beforeScrollStart', () => {
        this.$emit('beforeScroll')
      })
    }
  }

  disable() {
    this.scroll && this.scroll.disable()
  }
  enable() {
    this.scroll && this.scroll.enable()
  }
  refresh(index: number) {
    this.scroll && this.scroll.refresh()
    if (index === 2 && this.scroll && (this.scroll.x > this.scroll.maxScrollX)) {
      this.scroll.scrollTo(-index * 60, 0)
    } else {
      if (index === 2) {
        this.scroll.scrollTo(index * 60, 0)
      }
    }
  }
/*   scrollTo() {
    this.scroll && this.scroll.scrollTo.apply(this.scroll, ...[])
  }
  scrollToElement() {
    this.scroll && this.scroll.scrollToElement.apply(this.scroll, ...[])
  } */
}
</script>

<style lang="stylus" scoped></style>
